package stringMVC.controller;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;

@RequestMapping("/request")
@RestController
public class RequestController {
    @RequestMapping("/w1")
    //request和response是用到就加，没用到就不加
    public String getCookie(HttpServletRequest request, HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            //Arrays.stream(cookies).forEach(x -> System.out.println(x.getName() + ":" + x.getValue()));
            for (Cookie x : cookies) {
                System.out.println(x.getName() + ":" + x.getValue());
            }
            return "ok";
        }
        return "no";
    }
    @RequestMapping("/getCookie2")
    public String getCookie(@CookieValue("bite") Cookie cookie){
        return "bite : " + cookie.getValue();
    }
    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        String name = (String)session.getAttribute("username" );
        return name;
    }
    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("username","zhangsan");
        return "设置成功";
    }
    @RequestMapping("/getSession1")
    public String setSession1(HttpSession session){
        String name = (String)session.getAttribute("username" );
        return name;
    }

    @RequestMapping("/getSession2")
    public String getSession3(@SessionAttribute(value = "username",required = false) String username){
        return username;
    }
    @RequestMapping("/getHeader")
    public String getHeader(@RequestHeader("user-Agent") String user){
        return user;
    }
    @RequestMapping("/getHeader1")
    public String getHeader1(HttpServletRequest request){
        String user = request.getHeader("user-Agent");
        return user;
    }
}
